﻿Imports System.Web.Configuration
Imports log4net

Partial Class Encrypt
    Inherits System.Web.UI.Page
    Private provider As String = "RSAProtectedConfigurationProvider"
    Private section As String = "connectionStrings"
    Private section2 As String = "appSettings"
    Public scripttext As String = ""
	Private Shared logger As ILog = LogManager.GetLogger("ExportFrm")

    Protected Sub btnEncrypt_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnEncrypt.Click
        Try
            Dim confg As Configuration = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath)
            Dim confStrSect As ConfigurationSection = confg.GetSection(section)
            If Not confStrSect Is Nothing Then
                confStrSect.SectionInformation.ProtectSection(provider)
                Dim confStrSect2 As ConfigurationSection = confg.GetSection(section2)
                If Not confStrSect2 Is Nothing Then
                    confStrSect2.SectionInformation.ProtectSection(provider)
                End If
                confg.Save()
            End If

            
            ' the encrypted section is automatically decrypted!!
            scripttext = "<script>alert('ทำการเข้ารหัสเสร็จเรียบร้อยแล้ว')</script>"
        Catch ex As Exception
		logger.Error(ex.Message)
            logger.Error(ex.StackTrace)

            scripttext = "<script>alert('เกิดข้อผิดพลาด \n" & ex.Message & " ')</script>"
        End Try
    End Sub

    Protected Sub btnDecrypt_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnDecrypt.Click
        Try
            Dim confg As Configuration = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath)
            Dim confStrSect As ConfigurationSection = confg.GetSection(section)
            If Not confStrSect Is Nothing AndAlso confStrSect.SectionInformation.IsProtected Then
                confStrSect.SectionInformation.UnprotectSection()
                Dim confStrSect2 As ConfigurationSection = confg.GetSection(section2)
                If Not confStrSect2 Is Nothing Then
                    confStrSect2.SectionInformation.UnprotectSection()
                End If
                confg.Save()
            End If
            scripttext = "<script>alert('ทำการถอดรหัสเสร็จเรียบร้อยแล้ว')</script>"
        Catch ex As Exception
		logger.Error(ex.Message)
            logger.Error(ex.StackTrace)

            scripttext = "<script>alert('เกิดข้อผิดพลาด \n" & ex.Message & " ')</script>"
        End Try
    End Sub

    Protected Sub Okbtn_Click(sender As Object, e As EventArgs) Handles Okbtn.Click
        If Password.Text = ConfigurationManager.AppSettings("masterpassword") Then
            encryptdiv.Visible = True
            authendiv.Visible = False
        Else
            encryptdiv.Visible = False
            authendiv.Visible = True
        End If
    End Sub
End Class